<template>
  <div>
    <el-input
      v-model="filterText"
      placeholder="Filter keyword"
      style="width: 240px"
    />
    <el-tree
      ref="treeRef"
      :data="data"
      :props="defaultProps"
      class="filter-tree"
      default-expand-all
      draggable
      style="max-width: 600px"
      @node-drop="handleDrop"
      @node-click="handleNodeClick"
      :filter-node-method="filterNode"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { ElTree } from 'element-plus';

const props = defineProps<{
  data: any[];
  onNodeClick: (data: any) => void;
  onNodeDrop: (draggingNode: any, dropNode: any, dropType: any, ev: any) => void;
}>();

const filterText = ref('');
const treeRef = ref<InstanceType<typeof ElTree>>();

const defaultProps = {
  children: 'children',
  label: 'name',
};

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};

const handleNodeClick = (data: any) => {
  props.onNodeClick(data);
};

const handleDrop = (draggingNode: any, dropNode: any, dropType: any, ev: any) => {
  props.onNodeDrop(draggingNode, dropNode, dropType, ev);
};
</script>

<style scoped>
.filter-tree {
  max-width: 600px;
}
</style>
